//
//  TabBarViewController.swift
//  ManBetX
//
//  Created by Cocoa on 2020/3/16.
//  Copyright © 2020 Fullen. All rights reserved.
//

import UIKit

/**
 * TabBarViewController 相关
 */

class TabBarViewController: UITabBarController,UIGestureRecognizerDelegate {
    
// MARK: -- property

    var myTabBar = TabBar()
    var _loadView: UIView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        configureTabbar()
        
        customAddChild("首页", "tabbar_icon_home_unselected", "tabbar_icon_home_selected", HomeViewController.self, true)
        
        
//        customAddChild("优惠", "tabbar_icon_promotion_unselected", "tabbar_icon_promotion_selected", PromotionViewController.self, true)
        customAddChild("赞助", "tabbar_icon_promotion_unselected", "tabbar_icon_promotion_selected", SponsorViewController.self, false)
        
        
//        customAddChild("消息", "tabbar_icon_message_unselected", "tabbar_icon_message_selected", MessageViewController.self, true)
        customAddChild("助手", "tabbar_icon_message_unselected", "tabbar_icon_message_selected", HelperListVC.self, false)
        
        customAddChild("我的", "tabbar_icon_mine_unselected", "tabbar_icon_mine_selected", MineViewController.self, true)
        
        
        
        
        //tabBar 底部工具栏背景颜色 (以下两个都行)
//        self.tabBar.barTintColor = UIColor.clear
//        self.tabBar.backgroundColor = UIColor.white
    }
    
//    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
//        print(item.title)
//    }

    
    fileprivate func customAddChild(_ title: String,
                  _ image: String,
                  _ selectedImage: String,
                  _ type: UIViewController.Type,
                  _ xibFlag: Bool) {
        
        let viewController = xibFlag ? type.instanceFromStoryboard()! : type.init();
        
        // 当有Navigation和TabBar时，设置视图的显示范围
//        viewController.edgesForExtendedLayout = UIRectEdge.init()
        
        let childController = UINavigationController(rootViewController: viewController)
        childController.title = title
        childController.tabBarItem.image = UIImage(named: image)?.withRenderingMode(.alwaysOriginal)
        childController.tabBarItem.selectedImage =  UIImage(named: selectedImage)?.withRenderingMode(.alwaysOriginal)

        // 调整 tabBarItem titleLabel 往上偏移
        childController.tabBarItem.titlePositionAdjustment = UIOffset.init(horizontal: 0, vertical: -3)
         
        addChild(childController)
    }
    
    fileprivate func configureTabbar() {
        
        setValue(myTabBar, forKeyPath: "tabBar")
        
        // 修改 TabBarItem 选中时的属性
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.init("FFA855") ?? UIColor.yellow, NSAttributedString.Key.font: UIFont(name: "PingFangSC-Light", size: 13.0)!], for: .selected)

        // 修改 TabBarItem 未选中时的属性
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.init("929292") ?? UIColor.gray, NSAttributedString.Key.font: UIFont(name: "PingFangSC-Light", size: 13.0)!], for: .normal)
        
        // 绘制Layer
        drawLayer()
        // 底部工具栏背景颜色
        self.tabBar.shadowImage = UIImage.init()
        self.tabBar.backgroundImage = UIImage.init()
        
        myTabBar.centerButtonBlock = {
            self.kefuFunc()
        }
    }
    
    
    // 计算 layer point
    func getBezierPathPoint()-> NSMutableArray {
        
        let pointCount:Int = 4
        let buttonWidth:CGFloat = self.view.bounds.width/5
        let pointArr:NSMutableArray = NSMutableArray.init()
        for i in 0...pointCount {
            var px: CGFloat = 0
            var py: CGFloat = 0
            if i==0 {
                px = 0
            }else if i==1 {
                px = buttonWidth * 2.0 - 10.0
            }else if i==2 {
                px = self.view.bounds.width/2
                py = -15
            }else if i==3 {
                px = buttonWidth * 3.0 + 10.0
            }else if i==4 {
                px = self.view.bounds.width
            }
            let point: CGPoint = CGPoint.init(x: px, y: py)
            pointArr.add(point)
        }
        return pointArr
    }
    
    // 计算 layerShdow point
    func getBezierShdowPathPoint()-> NSMutableArray {
        
        let pointCount:Int = 4
        let buttonWidth:CGFloat = self.view.bounds.width/5
        let pointArr:NSMutableArray = NSMutableArray.init()
        for i in 0...pointCount {
            var px: CGFloat = 0
            var py: CGFloat = -1
            if i==0 {
                px = 0
            }else if i==1 {
                px = buttonWidth * 2.0 - 10.0
            }else if i==2 {
                px = self.view.bounds.width/2
                py = -16
            }else if i==3 {
                px = buttonWidth * 3.0 + 10.0
            }else if i==4 {
                px = self.view.bounds.width
            }
            let point: CGPoint = CGPoint.init(x: px, y: py)
            pointArr.add(point)
        }
        return pointArr
    }
    
    
    func drawBezierPath(pointArray:NSMutableArray) -> UIBezierPath {
        let bezierPath = UIBezierPath()
        bezierPath.lineWidth = 1.0
        var prevPoint: CGPoint!

        for i in 0 ..< pointArray.count {
            let currPoint:CGPoint = pointArray.object(at: i) as! CGPoint
            // 绘制平滑曲线
            if i==0 {
                bezierPath.move(to: currPoint)
            }else if i==(pointArray.count-1) {
                bezierPath.addLine(to: CGPoint.init(x: currPoint.x , y: currPoint.y))
            }else if i == 2 {
                let conPoint1: CGPoint = CGPoint.init(x: CGFloat(prevPoint.x + currPoint.x)/2 , y: prevPoint.y)
                let conPoint2: CGPoint = CGPoint.init(x: CGFloat(prevPoint.x + currPoint.x)/2, y: currPoint.y+5)// +5 是为了压低弧度
                bezierPath.addCurve(to: currPoint, controlPoint1: conPoint1, controlPoint2: conPoint2)
            }else if i == 3 {
                let conPoint1: CGPoint = CGPoint.init(x: CGFloat(prevPoint.x + currPoint.x)/2 , y: prevPoint.y+5)// +5 是为了压低弧度
                let conPoint2: CGPoint = CGPoint.init(x: CGFloat(prevPoint.x + currPoint.x)/2, y: currPoint.y)
                bezierPath.addCurve(to: currPoint, controlPoint1: conPoint1, controlPoint2: conPoint2)
            }else if i==(pointArray.count-1) {
                bezierPath.addLine(to: CGPoint.init(x: currPoint.x , y: currPoint.y))
            }else {
                let conPoint1: CGPoint = CGPoint.init(x: CGFloat(prevPoint.x + currPoint.x)/2 , y: prevPoint.y)
                let conPoint2: CGPoint = CGPoint.init(x: CGFloat(prevPoint.x + currPoint.x)/2, y: currPoint.y)
                bezierPath.addCurve(to: currPoint, controlPoint1: conPoint1, controlPoint2: conPoint2)
            }
            prevPoint = currPoint
        }
        
        // 中间凸起画个圆弧
        let circleBezierPath = UIBezierPath(arcCenter: CGPoint(x: self.view.bounds.width * 0.5, y: 9.8), radius: 25, startAngle: CGFloat.pi * 1.25, endAngle: CGFloat.pi * 1.75, clockwise: true)
        bezierPath.append(circleBezierPath)
        
        return bezierPath
    }
    
    // 添加Layer
    func drawLayer() {
        let bezierPath = self.drawBezierPath(pointArray: self.getBezierPathPoint())
        let bezierShdowPath = self.drawBezierPath(pointArray: self.getBezierShdowPathPoint())
        
        let shapeLayer = CAShapeLayer()
        
        shapeLayer.path = bezierPath.cgPath
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.strokeColor = UIColor.white.cgColor
        // 绘制tabbar中间凸出部分阴影
        shapeLayer.shadowPath = bezierShdowPath.cgPath
        shapeLayer.shadowColor = UIColor.black.cgColor
        shapeLayer.shadowOpacity = 0.05
        shapeLayer.shadowRadius = 3
        shapeLayer.shadowOffset = CGSize(width: 0, height: -2)
 
        self.tabBar.layer.insertSublayer(shapeLayer, at: 0)

        // 绘制tabbar阴影
        let path = CGMutablePath()
        path.addRect(self.tabBar.bounds)
        self.tabBar.layer.shadowPath = path
        path.closeSubpath()
        self.tabBar.layer.shadowColor = UIColor.black.cgColor
        self.tabBar.layer.shadowOffset = CGSize(width: 0, height: -2)
        self.tabBar.layer.shadowOpacity = 0.05
        self.tabBar.layer.shadowRadius = 3
    }
    
    func kefuFunc() {
    
        self._loadView = UIHelper.initLoadView(self, withMessage: "加载中...")
    
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        window.addSubview(self._loadView!)
        RequestHelper.post(atPath: "/ClientsAPIs/Comm100Api",withData:Dictionary(), withCompletion: { (data) in
        
            let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            
            //点击弹窗显示客服
            DispatchQueue.main.async {
                let success = dataArray?["success"] as? Bool ?? false
                
                if success  == true{
                   let data = dataArray?["data"] as? [String : Any] ?? [:]
                   let topDict = data["top"] as? [String : Any] ?? [:]
                    let topStatus = topDict["status"] as? Int ?? 0
                    if topStatus == 0{//不显示

                    }else{//显示

                    }
                    NetWorkRequest(API.checkAccessRight(url: "9a28015"), completion: { (responseData,statusCode,strData) -> (Void) in
                        DispatchQueue.main.async {
                            self._loadView!.removeFromSuperview()
                            let dataDict = responseData["data"].dictionary
                            let responseDict =  dataDict?["response"]?.dictionary
                            let c = responseDict?["c"]?.int ?? -1
                            let d = responseDict?["d"]?.dictionary
                            let m = responseDict?["m"]?.stringValue
                            if c == 0{
                                let phoneRecallAccessResult = d?["phoneRecallAccessResult"]?.boolValue
                                if phoneRecallAccessResult == false{ //没权限
                                     PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: false)
                                }else{//有权限
                                     PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: true)
                                }
                            }else{
                                UIHelper.alertSimpleMessage(about: "\(m ?? "")", withDescription: "", in: self)
                                PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: false)
                            }
                        }
                    }, failed: { (faildInfo,reCode,msg) -> (Void) in
                        
                       
                        DispatchQueue.main.async {
                            self._loadView?.removeFromSuperview()
                             // faildInfo - "未登录，请重新登录" - 先隐藏弹框
//                            UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                            PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: false)
                            }
                    }) { () -> (Void) in
                        DispatchQueue.main.async {
                            self._loadView?.removeFromSuperview()
                           UIHelper.alertSimpleMessage(about: "权限信息请求异常!", withDescription: "", in: self)
                            PopWindowHelper.showCustomerServicePopView(dict: dataArray?["data"] as? [String : Any] ?? [:],bgView: self.showBgView(),isShowCallBack: false)
                        }
                    }
                }else{
                    self._loadView?.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "获取客服信息失败。", withDescription: "", in: self)
                }
            }
        }) { (error) in
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "获取客服信息失败。", withDescription: "", in: self)
                self._loadView?.removeFromSuperview()
            }
        }
         ToolHelper.statisticsPage(pageName: "首页-底部导航-客服")
    }
    
    func showBgView()->UIView{
        let bgView :UIView  = UIView.init()
        bgView.backgroundColor = RGBAlpa(1,1,1,0.4)
        bgView.tag = 1200
//        bgView.isUserInteractionEnabled = true
//        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.hidenPop))
////         tapGesture.delegate = bgView.self as? UIGestureRecognizerDelegate
//        tapGesture.numberOfTapsRequired = 1
//        tapGesture.delegate = self
//        bgView.addGestureRecognizer(tapGesture)
        return bgView
    }
    
    @objc func hidenPop(){
        
        PopWindowHelper.closeShowCustomerServicePopView()
    }
}

